#!/usr/bin/env python
# encoding: utf-8
"""
environment.py

Created by  on 2007-11-01.
"""

import entity

#Environment class : holds all the entities in the game
class Environment:
    def __init__(self, file_name):
        self.entity_list = []
        self.deleted_list = []

        self.populate_from_file(file_name)
        
    #populates the entity list from a given file, returns 1 if successful
    def populate_from_file(self, file_name):
        try:
            f = open(file_name, "r")
            self.entity_list = eval(f.read().replace("\x0d",""))["environment"]
            for ent in self.entity_list:
                ent.environment = self
            f.close()
        except:
            self.entity_list = []
            return 0
        return 1
        
    #clears the entity list and trash
    def clear(self):
        self.entity_list = []
        self.deleted_list = []
        return 1
    
    #updates all entites and clears the deleted entities
    def update(self, time_passed, clients):
        self.update_entities(time_passed, clients)
        self.delete_entities()
    
    #iterates through and updates each entity
    def update_entities(self, time_passed, clients):
        for entity in self.entity_list:
            entity.update(time_passed, clients)

    def add_entity(self, new_entity):
        new_entity.environment = self
        self.entity_list.append(new_entity)
    
    #adds an entity to delete list, to be removed periodically, returns 1 if successful
    def remove_entity(self, entity):
        if entity in self.entity_list:
            self.deleted_list.append(entity)
            
    #removes all the deleted_list entities from the main entity list.
    def delete_entities(self):
        for entity in self.deleted_list:
            self.entity_list.remove(entity)
            